<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="订单流水" prop="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入订单流水"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="订单类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择订单类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PACKAGE_TRADE_ORDER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单来源" prop="terminal">
        <el-select
          v-model="queryParams.terminal"
          placeholder="请选择订单来源"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.TERMINAL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="会员ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入会员ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择订单状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PACKAGE_TRADE_ORDER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="代理人ID" prop="proxyUserId">
        <el-input
          v-model="queryParams.proxyUserId"
          placeholder="请输入代理人ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="购物车编号" prop="cartNo">
        <el-input
          v-model="queryParams.cartNo"
          placeholder="请输入购物车编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="取消类型" prop="cancelType">
        <el-select
          v-model="queryParams.cancelType"
          placeholder="请选择取消类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PACKAGE_TRADE_ORDER_CANCEL_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付订单ID" prop="payOrderId">
        <el-input
          v-model="queryParams.payOrderId"
          placeholder="请输入支付订单ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="是否支付" prop="payStatus">
        <el-select
          v-model="queryParams.payStatus"
          placeholder="请选择是否支付"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付渠道" prop="payChannelCode">
        <el-input
          v-model="queryParams.payChannelCode"
          placeholder="请输入支付渠道"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="退款类型" prop="refundType">
        <el-select
          v-model="queryParams.refundType"
          placeholder="请选择退款类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PACKAGE_TRADE_ORDER_REFUND_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['package:trade-order:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['package:trade-order:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="订单ID" align="center" prop="id" />
      <el-table-column label="订单名称" align="center" prop="title" />
      <el-table-column label="订单流水" align="center" prop="no" />
      <el-table-column label="订单类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PACKAGE_TRADE_ORDER_TYPE" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="订单来源" align="center" prop="terminal">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TERMINAL" :value="scope.row.terminal" />
        </template>
      </el-table-column>
      <el-table-column label="会员ID" align="center" prop="userId" />
      <el-table-column label="会员ip" align="center" prop="userIp" />
      <el-table-column label="会员备注" align="center" prop="userRemark" />
      <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PACKAGE_TRADE_ORDER_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="代理人ID" align="center" prop="proxyUserId" />
      <el-table-column label="配置清单ID" align="center" prop="cartNo" width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openCartDetail(scope.row.cartNo)"
          >
            详情
          </el-button>
          {{ scope.row.cartNo }}
        </template>
      </el-table-column>
      <el-table-column
        label="完成时间"
        align="center"
        prop="finishTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="取消时间"
        align="center"
        prop="cancelTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="取消类型" align="center" prop="cancelType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PACKAGE_TRADE_ORDER_CANCEL_TYPE" :value="scope.row.cancelType || 0" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="支付订单ID" align="center" prop="payOrderId" />
      <el-table-column label="是否支付" align="center" prop="payStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.payStatus" />
        </template>
      </el-table-column>
      <el-table-column
        label="支付时间"
        align="center"
        prop="payTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="支付渠道" align="center" prop="payChannelCode">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PAY_CHANNEL_CODE" :value="scope.row.payChannelCode || 'UNKNOW'" />
        </template>
      </el-table-column>
      <el-table-column label="原价(元)" align="center" prop="totalPrice" >
        <template #default="scope">
          {{ fenToYuan(scope.row.totalPrice) }}
        </template>
      </el-table-column>
      <el-table-column label="优惠金额(元)" align="center" prop="discountPrice" >
        <template #default="scope">
          {{ fenToYuan(scope.row.discountPrice) }}
        </template>
      </el-table-column>
      <el-table-column label="调价（正加，负减）" align="center" prop="adjustPrice" >
        <template #default="scope">
          {{ fenToYuan(scope.row.adjustPrice) }}
        </template>
      </el-table-column>
      <el-table-column label="应付金额" align="center" prop="payPrice" >
        <template #default="scope">
          {{ fenToYuan(scope.row.payPrice) }}
        </template>
      </el-table-column>
      <el-table-column label="退款类型" align="center" prop="refundType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PACKAGE_TRADE_ORDER_REFUND_TYPE" :value="scope.row.refundType || 0" />
        </template>
      </el-table-column>
      <el-table-column label="退款金额" align="center" prop="refundPrice" >
        <template #default="scope">
          {{ fenToYuan(scope.row.refundPrice) }}
        </template>
      </el-table-column>
      <el-table-column label="使用积分" align="center" prop="usePoint" />
      <el-table-column label="积分抵扣金额" align="center" prop="pointPrice" >
        <template #default="scope">
          {{ fenToYuan(scope.row.pointPrice) }}
        </template>
      </el-table-column>
      <el-table-column label="赠送积分" align="center" prop="givePoint" />
      <el-table-column label="退款退还积分" align="center" prop="refundPoint" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="关联租户ID" align="center" prop="relateTenantId"/>
      <el-table-column label="操作" align="center" width="106px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['package:trade-order:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['package:trade-order:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <el-dialog
    v-model="showDetail"
    title="订单详情"
    width="60%"
    destroy-on-close
    center
  >
    <el-descriptions :title="detail.title">
      <el-descriptions-item label="订单详情ID">{{ detail.cartId }}</el-descriptions-item>
      <el-descriptions-item label="套餐种类">{{ detail.packageCategoryName }}</el-descriptions-item>
      <el-descriptions-item label="套餐金额(元)">{{ fenToYuan(detail.packagePrice) }}</el-descriptions-item>
    </el-descriptions>
    <div class="m-t-20px"> </div>
    <el-descriptions title="套餐功能:"/>
    <el-table :data="detail.packageFunctions" stripe style="width: 100%">
      <el-table-column prop="functionId" label="功能ID" width="180" />
      <el-table-column prop="functionTypeName" label="功能类型" width="180" />
      <el-table-column prop="functionName" label="功能名称" />
    </el-table>
    <div class="m-t-20px"> </div>
    <el-descriptions title="增购功能:"/>
    <el-table :data="detail.children" stripe style="width: 100%">
      <el-table-column prop="itemId" label="功能ID" width="180" />
      <el-table-column prop="itemType" label="功能类型" width="180" />
      <el-table-column prop="itemName" label="功能名称" />
      <el-table-column prop="payPrice" label="增购金额(元)" >
        <template #default="scope">
          {{ fenToYuan(scope.row.payPrice) }}
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showDetail = false">关闭</el-button>
        <el-button type="primary" @click="showDetail = false">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 表单弹窗：添加/修改 -->
  <TradeOrderForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { TradeOrderApi, TradeOrderVO } from '@/api/package/trade/order/tradeorder'
import TradeOrderForm from './TradeOrderForm.vue'
import { fenToYuan } from '@/utils'

/** Saas订单 列表 */
defineOptions({ name: 'TradeOrder' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<TradeOrderVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const detail = ref()
const showDetail = ref(false) // 表单弹窗的显示
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  type: undefined,
  terminal: undefined,
  userId: undefined,
  status: undefined,
  proxyUserId: undefined,
  cartNo: undefined,
  cancelType: undefined,
  payOrderId: undefined,
  payStatus: undefined,
  payChannelCode: undefined,
  refundType: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TradeOrderApi.getTradeOrderPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 查询订单的配置清单详情 */
const openCartDetail = async (cartNo : string) => {
  detail.value = await TradeOrderApi.getTradeOrderDetail(cartNo)
  if (detail.value) {
    showDetail.value = true
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await TradeOrderApi.deleteTradeOrder(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TradeOrderApi.exportTradeOrder(queryParams)
    download.excel(data, 'Saas订单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>